import React, { useEffect, useState } from 'react'
import styles from './index.module.scss'
import ArticleItem from '../ArticleItem'
import { useDispatch, useSelector } from 'react-redux'
import { getArticleList, getMoreArticleList } from '@/store/actions/home'
import { PullToRefresh, InfiniteScroll } from 'antd-mobile-v5'
import { RootState } from '@/store'

type Props = {
  channelId: number
  activeId: number
}

export default function ArticleList({ channelId, activeId }: Props) {
  const dispatch = useDispatch()
  const current = useSelector(
    (state: RootState) => state.home.articles[channelId]
  )
  useEffect(() => {
    if (current) return // 有数据不发请求
    if (channelId === activeId) {
      dispatch(getArticleList(channelId, Date.now() + ''))
    }
  }, [channelId, activeId, dispatch, current])

  // 上拉更多状态
  const [hasMore, setHasMore] = useState(true)
  // 控制加载状态
  const [loading, setLoading] = useState(false)
  // 上拉加载更多
  const loadMore = async () => {
    // console.log('加载更多数据')
    if (loading) return
    if (channelId !== activeId) return //不是当前频道也不需要加载
    // 没有更多数据
    if (!current.timestamp) {
      setHasMore(false)
      return
    }
    // 正在加载
    setLoading(true)
    try {
      await dispatch(getMoreArticleList(channelId, current.timestamp))
    } finally {
      setLoading(false)
    }
  }

  // 不是当前频道，没有文章数据不渲染
  if (!current) return null

  // 下拉刷新
  const onRefresh = async () => {
    // 解决下拉刷新，不能上拉加载更多的问题
    setHasMore(true)
    // 下拉刷新加载最新的数据
    await dispatch(getArticleList(channelId, Date.now() + ''))
  }

  return (
    <div className={styles.root}>
      <div className="articles">
        {/* 下拉刷新 */}
        <PullToRefresh onRefresh={onRefresh}>
          {current.list.map((item) => (
            <div className="article-item" key={item.art_id}>
              <ArticleItem channelId={channelId} article={item}></ArticleItem>
            </div>
          ))}
        </PullToRefresh>

        {/* 上拉加载更多 */}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore}></InfiniteScroll>
      </div>
    </div>
  )
}
